import 'package:dio/dio.dart';
import 'package:enjoy_plus/models/user_info_model.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class UploadImage {
  static Future<String?> selectAvatar(BuildContext context) async {
    String? imageUrl = await showModalBottomSheet<String>(
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16),
              topRight: Radius.circular(16),
            ),
          ),
          height: 200,
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () async {
                  final url = await _pickImageFromCamera();
                  if (Navigator.canPop(context)) {
                    Navigator.pop(context, url);
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  foregroundColor: Colors.blue,
                  elevation: 0,
                  shadowColor: Colors.transparent,
                  minimumSize: Size(double.infinity, 50),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.camera_alt, color: Colors.black87),
                    SizedBox(width: 6),
                    Text('拍照', style: TextStyle(color: Colors.black87)),
                  ],
                ),
              ),
              ElevatedButton(
                onPressed: () async {
                  final url = await _pickImageFromGallery();
                  if (Navigator.canPop(context)) {
                    Navigator.pop(context, url);
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  foregroundColor: Colors.blue,
                  elevation: 0,
                  shadowColor: Colors.transparent,
                  minimumSize: Size(double.infinity, 50),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.photo, color: Colors.black87),
                    SizedBox(width: 6),
                    Text('相册', style: TextStyle(color: Colors.black87)),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );

    return imageUrl;
  }

  static Future<String> _pickImageFromGallery() async {
    return await _pickImage(ImageSource.gallery);
  }

  static Future<String> _pickImageFromCamera() async {
    return await _pickImage(ImageSource.camera);
  }

  static Future<String> _pickImage(ImageSource source) async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: source);

    if (pickedFile != null) {
      try {
        FormData formData = FormData.fromMap({
          "file": await MultipartFile.fromFile(pickedFile.path),
          "type": "avatar",
        });

        ToastUtil.showSuccess('正在上传图片，请稍等');
        var res = await http.post<UploadResponse>('/upload',
            data: formData, fromJson: (json) => UploadResponse.fromJson(json));
        if (res.code != 10000) {
          ToastUtil.showError('上传图片失败!');
          return '';
        }

        return res.data.url;
      } catch (e) {
        ToastUtil.showError('上传失败：${e.toString()}');
        return '';
      }
    }
    return '';
  }
}
